package com.plumecache.core.interceptor;

import com.plumecache.core.annotation.Key;
import com.plumecache.core.annotation.Value;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

/**
 * @author anson.yin
 * @date 2021/11/17 9:45 AM
 */
public abstract class BaseCacheInterceptor implements CacheInterceptor {
    protected void setKey(Method method, Object[] args, String newKey) {
        Integer keyIndex = getParameterIndex(method, Key.class);

        if (-1 == keyIndex) {
            return;
        }

        args[keyIndex] = newKey;
    }

    protected String getKey(Method method, Object[] args) {
        Integer keyIndex = getParameterIndex(method, Key.class);

        if (-1 != keyIndex) {
            return String.valueOf(args[keyIndex]);
        }
        
        return String.valueOf(args[0]);
    }

    protected Object getValue(Method method, Object[] args) {
        Integer valueIndex = getParameterIndex(method, Value.class);
        return args[valueIndex];
    }

    private <T extends Annotation> Integer getParameterIndex(Method method, Class<T> annotationClass) {
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            T keyAnnotation = parameters[i].getAnnotation(annotationClass);
            if (keyAnnotation != null) {
                return i;
            }
        }

        return -1;
    }
}
